package com.yuhuihui.common.utils;

import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Set;

/**
 * class工具类
 *
 * @author yuhh
 * @date 2023-05-25 14:06:51
 */
public final class ClassUtil {

    private static final Logger logger = LoggerFactory.getLogger(ClassUtil.class);

    /**
     * 根据指定类获取该类路径下的所有除自己之外的子类或实现类
     *
     * @param clazz 指定类
     * @return {@link ArrayList }<{@link T }> 除自己之外的子类或实现类
     * @author yuhh
     * @date 2023-05-25 14:07:00
     */
    public static <T>  ArrayList<T> getAllClass(Class<T> clazz){
        ArrayList<T> list =  new ArrayList<>();
        Reflections reflections = new Reflections(clazz.getPackage().getName());
        Set<Class<? extends T>> classes = reflections.getSubTypesOf(clazz);
        for (Class<? extends T> cls : classes) {
            if (!clazz.equals(cls)) {
                try {
                    list.add(cls.newInstance());
                } catch (Exception e){
                    logger.error("寻找class出现异常", e);
                }
            }
        }
        return list;
    }
}
